package com.example.practice.creative;

import java.util.ArrayList;
import java.util.List;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.example.practice.R;

public class BuyerAdapter extends BaseAdapter {
	private List<String> itemsList = new ArrayList<String>();

	public BuyerAdapter( List<String> itemsList) {
		 this.itemsList = itemsList;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return itemsList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		ShuiGuo shuiGuo;
		if(arg1 == null){
			shuiGuo = new ShuiGuo();
			arg1= LayoutInflater.from(arg2.getContext()).inflate(R.layout.item_buyer, null);
			shuiGuo.btnAdd = (Button)arg1.findViewById(R.id.btn_add);
			shuiGuo.btnDelete = (Button)arg1.findViewById(R.id.btn_delete);
			shuiGuo.txtContent = (TextView)arg1.findViewById(R.id.txt_content);
			shuiGuo.name = itemsList.get(arg0);
			shuiGuo.position = arg0;
			arg1.setTag(shuiGuo);
		}else{
			shuiGuo = (ShuiGuo)arg1.getTag();
		}
		
		shuiGuo.btnAdd.setTag(arg1);
		shuiGuo.btnDelete.setTag(arg1);
		
		shuiGuo.name = itemsList.get(arg0);
		float price = SPUtil.getFloat(shuiGuo.name);
		shuiGuo.txtContent.setText(shuiGuo.name + ":" + price + "*" + shuiGuo.count + "="+(price * shuiGuo.count));
		
		shuiGuo.btnAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				View view = (View)arg0.getTag();
				ShuiGuo shuiGuo = (ShuiGuo)view.getTag();
				shuiGuo.count++;
				view.setTag(shuiGuo);
				BuyerAdapter.this.notifyDataSetChanged();
			}
		});
		
		shuiGuo.btnDelete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				View view = (View)arg0.getTag();
				ShuiGuo shuiGuo = (ShuiGuo)view.getTag();
				shuiGuo.count--;
				shuiGuo.count = shuiGuo.count < 0 ? 0 : shuiGuo.count;
				view.setTag(shuiGuo);
				BuyerAdapter.this.notifyDataSetChanged();
			}
		});
		

		return arg1;
	}
	
	class ShuiGuo{
		Button btnAdd;
		Button btnDelete;
		TextView txtContent;
		String name;
		int count;
		int position;
	}
	
}
